const db = require('../config/database');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const logger = require('../utils/logger');

// JWT配置
const JWT_SECRET = process.env.ADMIN_JWT_SECRET || 'admin-secret-key-change-in-production-2024';
const JWT_EXPIRES_IN = '24h'; // 管理员token有效期24小时

/**
 * 管理员认证控制器
 */
class AdminAuthController {
  /**
   * 管理员登录
   * POST /api/admin/auth/login
   */
  async login(req, res) {
    try {
      const { username, password } = req.body;

      // 参数验证
      if (!username || !password) {
        return res.json({
          success: false,
          message: '用户名和密码不能为空'
        });
      }

      // 查询管理员
      const [admins] = await db.query(
        'SELECT * FROM admins WHERE username = ? AND status = 1',
        [username]
      );

      if (admins.length === 0) {
        logger.warn('管理员登录失败：用户不存在或已禁用', { username });
        return res.json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      const admin = admins[0];

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, admin.password);

      if (!isPasswordValid) {
        logger.warn('管理员登录失败：密码错误', { username });
        return res.json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      // 生成JWT Token
      const token = jwt.sign(
        {
          adminId: admin.id,
          username: admin.username,
          role: admin.role
        },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      // 更新最后登录信息
      await db.query(
        'UPDATE admins SET last_login_ip = ?, last_login_at = NOW() WHERE id = ?',
        [req.ip, admin.id]
      );

      // 记录操作日志
      await logOperation({
        admin_id: admin.id,
        admin_username: admin.username,
        operation_type: '登录',
        operation_module: '系统',
        ip_address: req.ip,
        user_agent: req.headers['user-agent']
      });

      logger.success('管理员登录成功', { 
        username: admin.username, 
        role: admin.role,
        ip: req.ip
      });

      // 返回登录信息（不包含密码）
      const adminInfo = {
        id: admin.id,
        username: admin.username,
        real_name: admin.real_name,
        role: admin.role,
        phone: admin.phone,
        email: admin.email
      };

      res.json({
        success: true,
        message: '登录成功',
        data: {
          token: token,
          adminInfo: adminInfo
        }
      });
    } catch (error) {
      logger.error('管理员登录异常', { error: error.message });
      res.json({
        success: false,
        message: '系统错误，请稍后重试'
      });
    }
  }

  /**
   * 获取管理员信息
   * GET /api/admin/auth/info
   */
  async getAdminInfo(req, res) {
    try {
      const adminId = req.admin.adminId;

      const [admins] = await db.query(
        'SELECT id, username, real_name, role, phone, email, created_at FROM admins WHERE id = ? AND status = 1',
        [adminId]
      );

      if (admins.length === 0) {
        return res.json({
          success: false,
          message: '管理员不存在或已禁用'
        });
      }

      res.json({
        success: true,
        data: admins[0]
      });
    } catch (error) {
      logger.error('获取管理员信息失败', { error: error.message });
      res.json({
        success: false,
        message: '系统错误'
      });
    }
  }

  /**
   * 修改密码
   * POST /api/admin/auth/change-password
   */
  async changePassword(req, res) {
    try {
      const adminId = req.admin.adminId;
      const { old_password, new_password } = req.body;

      if (!old_password || !new_password) {
        return res.json({
          success: false,
          message: '旧密码和新密码不能为空'
        });
      }

      if (new_password.length < 6) {
        return res.json({
          success: false,
          message: '新密码至少6位'
        });
      }

      // 查询管理员
      const [admins] = await db.query(
        'SELECT * FROM admins WHERE id = ?',
        [adminId]
      );

      if (admins.length === 0) {
        return res.json({
          success: false,
          message: '管理员不存在'
        });
      }

      const admin = admins[0];

      // 验证旧密码
      const isPasswordValid = await bcrypt.compare(old_password, admin.password);

      if (!isPasswordValid) {
        return res.json({
          success: false,
          message: '旧密码错误'
        });
      }

      // 加密新密码
      const hashedPassword = await bcrypt.hash(new_password, 10);

      // 更新密码
      await db.query(
        'UPDATE admins SET password = ?, updated_at = NOW() WHERE id = ?',
        [hashedPassword, adminId]
      );

      // 记录操作日志
      await logOperation({
        admin_id: adminId,
        admin_username: admin.username,
        operation_type: '修改密码',
        operation_module: '系统',
        ip_address: req.ip,
        user_agent: req.headers['user-agent']
      });

      logger.success('管理员修改密码成功', { username: admin.username });

      res.json({
        success: true,
        message: '密码修改成功，请重新登录'
      });
    } catch (error) {
      logger.error('修改密码失败', { error: error.message });
      res.json({
        success: false,
        message: '系统错误'
      });
    }
  }

  /**
   * 退出登录
   * POST /api/admin/auth/logout
   */
  async logout(req, res) {
    try {
      const admin = req.admin;

      // 记录操作日志
      await logOperation({
        admin_id: admin.adminId,
        admin_username: admin.username,
        operation_type: '退出登录',
        operation_module: '系统',
        ip_address: req.ip,
        user_agent: req.headers['user-agent']
      });

      logger.info('管理员退出登录', { username: admin.username });

      res.json({
        success: true,
        message: '已退出登录'
      });
    } catch (error) {
      logger.error('退出登录失败', { error: error.message });
      res.json({
        success: false,
        message: '系统错误'
      });
    }
  }

}

/**
 * 记录操作日志（独立函数）
 */
async function logOperation(logData) {
  try {
    await db.query(
      `INSERT INTO admin_operation_logs 
       (admin_id, admin_username, operation_type, operation_module, operation_detail, target_id, ip_address, user_agent, result) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        logData.admin_id || null,
        logData.admin_username || null,
        logData.operation_type,
        logData.operation_module,
        logData.operation_detail || null,
        logData.target_id || null,
        logData.ip_address || null,
        logData.user_agent || null,
        logData.result || 'success'
      ]
    );
  } catch (error) {
    console.error('记录操作日志失败:', error);
  }
}

module.exports = new AdminAuthController();
module.exports.JWT_SECRET = JWT_SECRET;
module.exports.JWT_EXPIRES_IN = JWT_EXPIRES_IN;
module.exports.logOperation = logOperation;

